<?php
require_once("config.inc.php");
require_once("weibo.php");
require_once("db.class.php");
require_once("lunar.class.php");
header( "Content-Type:text/html; charset=utf-8" );
$wb = new weibo(APP_KEY, SECRET_KEY);
$wb->setUser( USER_NAME , USER_PASS );

if( $ms = $wb->mentions() )
{
	//print_r($ms);
	$db = new db($site_Db);
	$ld = new Lunar();
	$ms=array_reverse($ms);
	foreach( $ms as $item )
	{
		//只处理固定格式
		$text = trim($item['text']);
		preg_match("/^(.+?)\s*@时间助手$/", $text, $match);
		if(!empty($match[0])) {
			//判断是否已处理
			$max = $db->fetchone("SELECT MAX(cid) AS max FROM mention");
			if( $item['id'] > $max )
			{
				if($db->query("INSERT INTO mention VALUES(null, ".$item['id'].", '".$item['text']."', ".time().", 0)"))
					echo "Add a new mention.";
	
				
				//$text = trim(reset(explode('@时间助手',$text)));
				$schars = explode( "|" , '.|。|,|、|！|？|：|；|`|﹑|•|＂|^|…|‘|’|“|”|〝|〞|~|\|〖|〗|《|》|『|』|【|】|—|(|)|[|]|{|}|﹝|﹞|﹛|﹜|〔|〕|（|）' );
				$text = str_replace( $schars , '' , $match[1] );
				$cmd = explode(' ',$text);
				$type =$cmd[0];
				switch ($type) {
					case "wnl":
						$re=deal_wnl($cmd[1]);
						break;
					default:
						$re='';
				}
				if(!empty($re)) {
					$comment = $re;
				} else {
					$comment = '系统无法执行您的请求，请检查您查询的格式，您查询的内容为：' . $text . '！ 查询格式示例：wnl 2010/(0)1/(0)1@时间助手';
				}
				if($wb->send_comment( $item['id'] , $comment ))
					echo "deal success.";
			} else {
				echo "No mention deal.";
			}
		}
	}
}

function deal_wnl($datestr) {
	global $ld;
	if(!empty($datestr)) {
		preg_match("/([0-9]{1,4})\/([0-9]{1,2})\/([0-9]{1,2})/", $datestr, $date);
		if(count($date)==4&&!empty($date[1])&&!empty($date[2])&&!empty($date[3])) {
			if($date[1]>0&&$date[1]<9999&&$date[2]>0&&$date[2]<13&&$date[3]>0&&$date[3]<32) {
				$year=intval($date[1]);$month=intval($date[2]);$day=intval($date[3]);
			} else {
				return;
			}
		} else {
			return ;
		}
	} else {
		$date = date("Y-n-j",time());
		list($year,$month,$day) = explode('-',$date);
	}
	$ld->calc($year,$month,$day);
	$lddis=$ld->display();
	$week=get_Week($year,$month,$day);
	return $year."年".$month."月".$day."日：".$lddis." ".$week;
}

function get_Week($y,$m,$d) {
	$iweek=date("w",mktime(0,0,0,$m,$d,$y));
	switch($iweek) {
		case 0:
	    	$sweek = '星期天';
	    	break;
	    case 1:
	    	$sweek = '星期一';
	    	break;
	    case 2:
	    	$sweek = '星期二';
	    	break;
	    case 3:
	    	$sweek = '星期三';
	    	break;
	    case 4:
	    	$sweek = '星期四';
	    	break;
	    case 5:
	    	$sweek = '星期五';
	    	break;
	    case 6:
	    	$sweek = '星期六';
	    	break;
	}
	return $sweek;
}
?>